package com.ruoyi.web.controller.system.fuw;

import java.io.IOException;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.fuw.domain.FuwCar;
import com.ruoyi.fuw.domain.FuwMessage;
import com.ruoyi.fuw.service.IFuwMessageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 消息记录Controller
 * 
 * @author ruoyi
 * @date 2021-11-14
 */
@RestController
@RequestMapping("/fuw/message")
public class FuwMessageController extends BaseController
{
    @Autowired
    private IFuwMessageService fuwMessageService;

    /**
     * 查询消息记录列表
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:list')")
    @GetMapping("/list")
    public TableDataInfo list(FuwMessage fuwMessage)
    {
        startPage();
        List<FuwMessage> list = fuwMessageService.selectFuwMessageList(fuwMessage);
        return getDataTable(list);
    }

    /**
     * 查询消息记录列表
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:list')")
    @GetMapping("/list/message")
    public AjaxResult listMessageAll(FuwMessage fuwMessage)
    {
        List<FuwMessage> listAll = new ArrayList<>();
        List<FuwMessage> listFrom = new ArrayList<>();
        List<FuwMessage> listTo = new ArrayList<>();

        FuwMessage fuwMessageFrom = new FuwMessage();
        fuwMessageFrom.setFrom(fuwMessage.getTo());
        fuwMessageFrom.setTo(fuwMessage.getFrom());
        listFrom = fuwMessageService.selectFuwMessageList(fuwMessageFrom);
        listAll.addAll(listFrom);
        FuwMessage fuwMessageTo = new FuwMessage();
        fuwMessageTo.setFrom(fuwMessage.getFrom());
        fuwMessageTo.setTo(fuwMessage.getTo());
        listTo = fuwMessageService.selectFuwMessageList(fuwMessageTo);
        listAll.addAll(listTo);

        Collections.sort(listAll, new Comparator<FuwMessage>() {
            Collator collator = Collator.getInstance(Locale.CHINA);
            @Override
            public int compare(FuwMessage o1, FuwMessage o2) {
                CollationKey key1 = collator.getCollationKey(String.valueOf(o1.getChatTime().getTime()));
                CollationKey key2 = collator.getCollationKey(String.valueOf(o2.getChatTime().getTime()));
                return key1.compareTo(key2);
            }
        });

        return AjaxResult.success(listAll);
    }

    /**
     * 查询存在未读消息的人员
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:list')")
    @GetMapping("/list/unread")
    public AjaxResult listUnread(FuwMessage fuwMessage)
    {
        fuwMessage.setChatType("1");
        fuwMessage.setTo(getUsername());
        List<FuwMessage> list = fuwMessageService.selectFuwMessageList(fuwMessage);

        String unreadName = "";

        // 验证数据的map
        Map<String, Object> map = new HashMap<>();
        for(FuwMessage message: list){
            if(map.get(message.getFrom()) == null){
                map.put(message.getFrom(), message.getFrom());
                unreadName = unreadName + message.getFrom() + ",";
            }
        }

        return AjaxResult.success(unreadName);
    }

    /**
     * 导出消息记录列表
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:export')")
    @Log(title = "消息记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FuwMessage fuwMessage)
    {
        List<FuwMessage> list = fuwMessageService.selectFuwMessageList(fuwMessage);
        ExcelUtil<FuwMessage> util = new ExcelUtil<FuwMessage>(FuwMessage.class);
        return util.exportExcel(list, "消息记录数据");
    }

    /**
     * 获取消息记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:query')")
    @GetMapping(value = "/{uId}")
    public AjaxResult getInfo(@PathVariable("uId") Long uId)
    {
        return AjaxResult.success(fuwMessageService.selectFuwMessageByUId(uId));
    }

    /**
     * 新增商品信息
     */
    @PreAuthorize("@ss.hasPermi('fuw:comm:add')")
    @PostMapping(value = "/upload")
    public AjaxResult upload(MultipartFile file)
    {
        // 根据文件路径上传
        String fullPath = "";
        if(file != null){
            try {
                fullPath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            fullPath = "http://localhost/dev-api" + fullPath;
        }

        return AjaxResult.success(fullPath);
    }

    /**
     * 新增消息记录
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:add')")
    @Log(title = "消息记录", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResult add(@RequestParam("from") String from,
                          @RequestParam("to") String to,
                          @RequestParam("chatText") String chatText)
    {
        // 创建消息
        FuwMessage fuwMessage = new FuwMessage();
        fuwMessage.setFrom(from);
        fuwMessage.setTo(to);
        fuwMessage.setChatText(chatText);

        // 获取当前时间
        fuwMessage.setChatTime(DateUtils.parseDate(DateUtils.getTime()));
        // 消息状态，默认为0：消息创建
        fuwMessage.setChatType("1");

        return AjaxResult.success(fuwMessageService.insertFuwMessage(fuwMessage));
    }

    /**
     * 修改消息记录
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:edit')")
    @Log(title = "消息记录", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update")
    public AjaxResult edit(@RequestParam("from") String from,
                           @RequestParam("to") String to)
    {
        FuwMessage fuwMessageTo = new FuwMessage();
        fuwMessageTo.setFrom(to);
        fuwMessageTo.setTo(from);
        List<FuwMessage> list = fuwMessageService.selectFuwMessageList(fuwMessageTo);

        for(int i=0; i<list.size(); i++){
            // 消息状态修改
            list.get(i).setChatType("2");
            // 获取当前时间
            list.get(i).setChatEndTime(DateUtils.parseDate(DateUtils.getTime()));
            // 修改信息
            fuwMessageService.updateFuwMessage(list.get(i));
        }

        return AjaxResult.success();
    }

    /**
     * 删除消息记录
     */
    @PreAuthorize("@ss.hasPermi('fuw:message:remove')")
    @Log(title = "消息记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{uIds}")
    public AjaxResult remove(@PathVariable Long[] uIds)
    {
        return toAjax(fuwMessageService.deleteFuwMessageByUIds(uIds));
    }
}
